const request = (url, options) => {
    return new Promise((resolve, reject) => {
        const app = getApp()
        wx.request({
            url: url,
            method: options.method,
            data: options.data,
            header: {
                'Content-Type': options.method === 'GET' ? 'application/json; charset=UTF-8' : 'application/x-www-form-urlencoded',
                'sessionId': app.globalData.sessionId,
                'openId': app.globalData.openId
            },
            success(request) {
                // 约定 20000 为成功
                if (request.data.code === 20000) {
                    resolve(request.data)
                } else {
                    reject(request.data)
                }
            },
            fail(error) {
                reject(error.data)
            }
        })
    })
}

const get = (url, options = {}) => {
    return request(url, {
        method: 'GET',
        data: options
    })
}

const post = (url, options) => {
    return request(url, {
        method: 'POST',
        data: options
    })
}

const put = (url, options) => {
    return request(url, {
        method: 'PUT',
        data: options
    })
}

// 不能声明DELETE（关键字）
const remove = (url, options) => {
    return request(url, {
        method: 'DELETE',
        data: options
    })
}

module.exports = {
    get,
    post,
    put,
    remove
}